<?php

namespace Romolo\Snitso\Blocking;


class Worker
{
    protected $socket;
    public $onConnect = null;
    public $onReceive = null;
    public $onClose = null;

    public function __construct(string $address)
    {
        $this->socket = stream_socket_server($address);
    }

    public function start()
    {
        $this->accept();
    }

    private function accept()
    {
        while (true) {
            $client = stream_socket_accept($this->socket);

            /*$message = fread($client, 1024);
            echo "I have received that:" . $message;

            fwrite($client, 'The local time is ' . date('n/j/Y g:i a') . "\n");
            fclose($client);*/

            ($this->onConnect)($this, $client);

            $data = fread($client, 65535);
            ($this->onReceive)($this, $client, $data);

            // fclose($client);
        }
    }

    public function send($client, $data)
    {
        $response = "HTTP/1.1 200 OK\r\n";
        $response .= "Content-Type: text/html;charset=UTF-8\r\n";
        $response .= "Connection: keep-alive\r\n";
        $response .= "Content-length: ".strlen($data)."\r\n\r\n";
        $response .= $data;
        fwrite($client, $response);
    }
}